// serial.c
#include "serial_c.h"
#include <windows.h>  // Windows系统使用
// #include <termios.h>  // Linux系统使用
#include <stdio.h>

HANDLE serialHandles[16] = {NULL};  // 存储串口句柄

int openSerial(const char* portName, int baudRate) {
    HANDLE hSerial;
    DCB dcbSerialParams = {0};
    COMMTIMEOUTS timeouts = {0};
    
    // 打开串口
    hSerial = CreateFile(portName,
                        GENERIC_READ | GENERIC_WRITE,
                        0,
                        NULL,
                        OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);
                        
    if (hSerial == INVALID_HANDLE_VALUE) {
        return -1;
    }
    
    // 配置串口参数
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    if (!GetCommState(hSerial, &dcbSerialParams)) {
        CloseHandle(hSerial);
        return -1;
    }
    
    dcbSerialParams.BaudRate = baudRate;
    dcbSerialParams.ByteSize = 8;
    dcbSerialParams.StopBits = ONESTOPBIT;
    dcbSerialParams.Parity = NOPARITY;
    
    if (!SetCommState(hSerial, &dcbSerialParams)) {
        CloseHandle(hSerial);
        return -1;
    }
    
    // 设置超时
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;
    
    if (!SetCommTimeouts(hSerial, &timeouts)) {
        CloseHandle(hSerial);
        return -1;
    }
    
    // 存储句柄并返回索引
    for (int i = 0; i < 16; i++) {
        if (serialHandles[i] == NULL) {
            serialHandles[i] = hSerial;
            return i;
        }
    }
    
    CloseHandle(hSerial);
    return -1;
}

void closeSerial(int handle) {
    if (handle >= 0 && handle < 16 && serialHandles[handle] != NULL) {
        CloseHandle(serialHandles[handle]);
        serialHandles[handle] = NULL;
    }
}

int sendData(int handle, const unsigned char* data, int length) {
    DWORD bytesWritten;
    
    if (handle < 0 || handle >= 16 || serialHandles[handle] == NULL) {
        return -1;
    }
    
    if (!WriteFile(serialHandles[handle], data, length, &bytesWritten, NULL)) {
        return -1;
    }
    
    return bytesWritten;
}

int receiveData(int handle, unsigned char* buffer, int bufferSize) {
    DWORD bytesRead;
    
    if (handle < 0 || handle >= 16 || serialHandles[handle] == NULL) {
        return -1;
    }
    
    if (!ReadFile(serialHandles[handle], buffer, bufferSize, &bytesRead, NULL)) {
        return -1;
    }
    
    return bytesRead;
}
